package com.sdy.hospitalguard.web.config;

import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.support.http.StatViewServlet;
import com.sdy.mvc.utils.DruidManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@ComponentScan(basePackageClasses = {DruidManager.class})
@PropertySource("file:/opt/config/hospital-guard/appConfig.properties")
public class DruidConfig {

    @Value("${druid.username}")
    private String druidUsername;

    @Value("${druid.password}")
    private String druidPassword;

    @Value("${druid.allow:}")
    private String druidAllow;

    @Value("${druid.deny:}")
    private String druidDeny;

    @Value("${druid.resetEnable:true}")
    private String druidResetEnable;

    @Bean
    public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(),  "/druid/*");
        // IP白名单 (没有配置或者为空，则允许所有访问)
        registrationBean.addInitParameter("allow", druidAllow);
        // IP黑名单 (存在共同时，deny优先于allow)
        registrationBean.addInitParameter("deny", druidDeny);
        registrationBean.addInitParameter("loginUsername", druidUsername);
        registrationBean.addInitParameter("loginPassword", druidPassword);
        registrationBean.addInitParameter("resetEnable", druidResetEnable);
        return registrationBean;
    }

    @Bean
    public Slf4jLogFilter logFilter() {
        Slf4jLogFilter logFilter = new Slf4jLogFilter();
        logFilter.setStatementLogEnabled(true);
        logFilter.setStatementExecutableSqlLogEnable(true);
        logFilter.setStatementCreateAfterLogEnabled(false);
        logFilter.setStatementCloseAfterLogEnabled(false);
        logFilter.setStatementExecuteAfterLogEnabled(false);
        logFilter.setStatementParameterSetLogEnabled(false);
        logFilter.setStatementPrepareAfterLogEnabled(false);
        logFilter.setConnectionConnectBeforeLogEnabled(false);
        logFilter.setConnectionConnectAfterLogEnabled(false);
        logFilter.setResultSetCloseAfterLogEnabled(false);
        return logFilter;
    }

    @Bean
    public StatFilter statFilter() {
        StatFilter statFilter = new StatFilter();
        statFilter.setLogSlowSql(true);
        statFilter.setSlowSqlMillis(1000);
        statFilter.setMergeSql(true);
        return statFilter;
    }
}
